package com.project.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration//标识该类为配置类
@ComponentScan("com.project")//扫描指定包及子包中的spring组件
@MapperScan("com.project.mapper")//扫描指定包中的mapper文件
@EnableTransactionManagement//提供事务支持
public class MyBatisConfig {
    /**
     * 配置数据源
     * @return
     */
    @Bean//标识该方法返回的对象为spring组件
    public DataSource getData(){
        //连接池对象
        DruidDataSource dataSource = new DruidDataSource();

        //设置驱动
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        //设置URL
        dataSource.setUrl("jdbc:mysql://localhost:3306/users?characterEncoding=utf8&allowMultiQueries=true");
        //设置mysql的登录用户名和密码
        dataSource.setUsername("root");
        dataSource.setPassword("083651");

        //设置连接池最大最小连接数
        dataSource.setMaxActive(100);
        dataSource.setMinIdle(20);
        //设置最大等待时间
        dataSource.setMaxWait(1000);

        return dataSource;
    }

    /**
     * 配置会话工厂
     * @return 会话工厂
     */
    @Bean
    public SqlSessionFactoryBean getFactory(){
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        //设置数据源
        factoryBean.setDataSource(this.getData());
        //加载mybatis的主配置文件
        factoryBean.setConfigLocation(new ClassPathResource("mybatis.cfg.xml"));

        return factoryBean;
    }

    /**
     * 配置事务管理器
     * @return 事务管理器对象
     */
    @Bean
    public TransactionManager getTransactionManager(){
        DataSourceTransactionManager manager = new DataSourceTransactionManager();
        manager.setDataSource(getData());
        return manager;
    }
}
